﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FisheryPlatform.Common.StaticCache;
using System.IO;
using System.Web.UI;
using System.Net;
using System.Configuration;
using FisheryPlatform.Entity;
using FisheryPlatform.Bussiness.Account;
using FisheryPlatform.Bussiness.LoginCookie;
using FisheryPlatform.SiteConfig;
using FisheryPlatform.SiteConfig.FileStore;
using FisheryPlatform.Bussiness.Product;
using FisheryPlatform.Bussiness.FileStore;
using FisheryPlatform.Common;

namespace FisheryPlatform.Bussiness.Cache
{
    /// <summary>
    /// 产品静态html缓存
    /// </summary>
    public class ProductStaticHtmlCache
    {
        public static string GetFileName(string productId, DateTime createDate)
        {
            var uploadFile = new UploadFileEntity(productId, ProductStaticHtmlUploadProvider.defaultExtensionName, new byte[] { });
            uploadFile.UploadDate = createDate;
            ProductStaticHtmlUploadProvider productUpload = new ProductStaticHtmlUploadProvider(uploadFile);
            return uploadFile.PublishUrl + uploadFile.PublishUrlPath;
        }

        /// <summary>
        /// 获取缓存文件
        /// </summary>
        /// <param name="publishUrlPath"></param>
        /// <returns></returns>
        public static string Get(string publishUrlPath)
        {
            #region

            var text = ProductStaticHtmlUploadProvider.GetFileContent(publishUrlPath);
            if (string.IsNullOrEmpty(text))
            {
                var productId = Path.GetFileNameWithoutExtension(publishUrlPath);
                text = GetProductInfo(productId);
                if (!string.IsNullOrEmpty(text))
                {
                    var proInfo = ProductManager.Get(long.Parse(productId));
                    var uploadFile = new UploadFileEntity(productId, ProductStaticHtmlUploadProvider.defaultExtensionName, Encoding.Default.GetBytes(text));
                    uploadFile.UploadDate = proInfo.CreateDate;
                    ProductStaticHtmlUploadProvider productUpload = new ProductStaticHtmlUploadProvider(uploadFile);
                    productUpload.Save();
                }
            }
            //var text = CacheFileUtility.Instance.GetText(fileName);
            //if (string.IsNullOrEmpty(text))
            //{
            //    var segment = fileName.Split('_');
            //    text = GetProductInfo(segment[segment.Length - 1]);
            //    if (string.IsNullOrEmpty(text) == false)
            //        Cache(fileName, ASCIIEncoding.Default.GetBytes(text));
            //}
            //var adminUserInfo = new LoginUserInfo().AdminUserInfo;
            //text = text.Replace("{_contact_}", adminUserInfo.RealName);
            //var imgUrl = SiteConfigManager.AppSettings["ContractPhoneUrl"].Value ?? "/Ajax/ContactInfo.ashx?type=100&proCode=" + fileName + "&rn=" + new Random().NextDouble();
            //text = text.Replace("{_contact_phone_}", imgUrl);
            //return text;
            return text;
            #endregion
        }

        public static string GetProductInfo(string productId)
        {
            #region
            var resposeText = "";
            try
            {
                var url = (SiteConfigManager.AppSettings["GenerateStaticHtmlUrl.Pro"].Value ?? SiteConfigManager.WebSite.WWW + "/Product/Details.aspx?proCode=") + productId;
                //request
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.Method = "GET";
                request.UserAgent = "LaoZhouYuYe--Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                //request.ContentLength = buffer.Length;
                // request.ClientCertificates.Add(new X509Certificate2(ConfigSetting.ConfigInfo.CertPath + ConfigSetting.ConfigInfo.CertFileName, ConfigSetting.ConfigInfo.KeyPassword));
                request.KeepAlive = true;
                //using (Stream reqStream = request.GetRequestStream())
                //{
                //    reqStream.Write(buffer, 0, buffer.Length);
                //}

                //response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    resposeText = reader.ReadToEnd();
                }
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    resposeText = "";
                }
                response.Close();
            }
            catch (Exception e)
            {
                Exception ex = new Exception(e.ToString());
                ExceptionMessage.Record(ex);
            }
            return resposeText;
            #endregion
        }

        /// <summary>
        /// 删除缓存文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void Delete(long productId)
        {
            #region
            var proInfo = ProductManager.Get(productId);

            //联系电话图片s
            UploadFileEntity uploadFile = new UploadFileEntity(proInfo.ProductId.ToString(), "proid.jpg", new byte[] { });// ImageUtility.ContactPhone(phone)
            uploadFile.UploadDate = proInfo.CreateDate;//必须得
            ContactInfoImageUploadProvider imageUpload = new ContactInfoImageUploadProvider(uploadFile);
            imageUpload.Delete();

            //产品静态页面
            uploadFile = new UploadFileEntity(proInfo.ProductId.ToString(), ProductStaticHtmlUploadProvider.defaultExtensionName, new byte[] { });
            uploadFile.UploadDate = proInfo.CreateDate;
            ProductStaticHtmlUploadProvider productUpload = new ProductStaticHtmlUploadProvider(uploadFile);
            productUpload.Delete();
            #endregion
        }
    }
}
